let layer = layui.layer;
let form = layui.form;
let q = {
  pagenum: 1, // 页码值，默认请求第一页的数据
  pagesize: 2, // 每页显示几条数据，默认每页显示2条
  cate_id: "", // 文章分类的 Id
  state: "", // 文章的发布状态
};

// 获取列表数据函数
function initTable() {
  $.ajax({
    method: "GET",
    url: "/my/article/list",
    data: q,
    success: (res) => {
      if (res.status !== 0) return layer.msg(res.message);
      layer.msg(res.message);
      let htmlstl = template("tpl-table", res);
      $("tbody").html(htmlstl);
      renderPage(res.total);
    },
  });
}
initTable();
initCate();

// 定义美化时间的过滤器
template.defaults.imports.dataFormat = function (date) {
  const dt = new Date(date);

  var y = dt.getFullYear();
  var m = padZero(dt.getMonth() + 1);
  var d = padZero(dt.getDate());

  var hh = padZero(dt.getHours());
  var mm = padZero(dt.getMinutes());
  var ss = padZero(dt.getSeconds());

  return y + "-" + m + "-" + d + " " + hh + ":" + mm + ":" + ss;
};
// 定义补零的函数
function padZero(n) {
  return n > 9 ? n : "0" + n;
}

function initCate() {
  $.ajax({
    method: "GET",
    url: "/my/article/cates",
    success: (res) => {
      if (res.status !== 0) return layer.msg(res.message);
      layer.msg(res.message);
      let htmlSta = template("tpl_cate", res);
      $("[name=cate_id]").html(htmlSta);
      form.render();
    },
  });
}

$("#form-search").on("submit", function (e) {
  e.preventDefault();
  let cate_id = $('[name="cate_id"]').val();
  let state = $('[name="state"]').val();
  q.cate_id = cate_id;
  q.state = state;
  initTable();
});

// 定义渲染分页的方法
function renderPage(total) {
  // 调用 laypage.render() 方法来渲染分页的结构
  layui.laypage.render({
    elem: "pageBox", // 分页容器的 Id
    count: total, // 总数据条数
    limit: q.pagesize, // 每页显示几条数据
    curr: q.pagenum, // 设置默认被选中的分页
    layout: ["count", "limit", "prev", "page", "next", "skip"],
    limits: [2, 4, 6, 8, 10],
    jump: (obj, first) => {
      q.pagenum = obj.curr;
      q.pagesize = obj.limit;
      if (!first) {
        initTable();
      }
    },
  });
}

$("tbody").on("click", ".btn_list", function () {
  let length = $(".btn_list").length;
  let id = $(this).attr("data-id");
  layer.confirm("确认删除?", { icon: 3, title: "提示" }, function (index) {
    $.ajax({
      method: "GET",
      url: "/my/article/delete/" + id,
      success: (res) => {
        if (res.status !== 0) return layer.msg(res.message);
        layer.msg(res.message);
        if (length === 1) {
          q.pagenum = q.pagenum === 1 ? 1 : q.pagenum - 1;
        }
        initTable();
        layer.close(index);
      },
    });
  });
});
